package com.atguigu.xuexiplus.mapper;

import com.atguigu.xuexiplus.dto.UserDTO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;

@Mapper
public interface Usermapper {
    // 登录 - 先根据用户名查询，然后在代码中验证密码
    @Select("select id, username, nickname, avatar_url as avatarUrl, role, random_code as randomCode, password, status from user where username = #{username}")
    UserDTO findByUsername(@Param("username") String username);
    
    // 根据ID查询用户（完整字段）
    @Select("select id, username, nickname, avatar_url as avatarUrl, role, random_code as randomCode, password, status, created_at as createdAt, updated_at as updatedAt from user where id = #{id}")
    UserDTO findById(@Param("id") Long id);

    // 更新个人资料（仅修改提供的字段）
    @Update("UPDATE user SET \n" +
            "nickname = COALESCE(#{nickname}, nickname),\n" +
            "avatar_url = COALESCE(#{avatarUrl}, avatar_url),\n" +
            "updated_at = NOW()\n" +
            "WHERE id = #{userId}")
    int updateProfile(@Param("userId") Long userId,
                      @Param("nickname") String nickname,
                      @Param("avatarUrl") String avatarUrl);
    
    // 更新用户状态
    @Update("UPDATE user SET status = #{status} WHERE username = #{username}")
    int updateStatus(@Param("username") String username, @Param("status") Integer status);

    // 查询所有用户（含在线状态）
    @Select("SELECT id, username, nickname, avatar_url as avatarUrl, role, random_code as randomCode, status FROM user ORDER BY status DESC, nickname ASC")
    List<com.atguigu.xuexiplus.entity.User> listAllUsers();
}
